package com.hailiao.devicebasicsdkdemo.utils

import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout

/**
 * @author D10NG
 * @date on 2020/8/7 5:29 PM
 */

/**
 * 解决RecyclerView与SwipeRefreshLayout下拉动作的冲突
 * @param srLayout SwipeRefreshLayout
 */
fun RecyclerView.fixSwipeRefreshClash(srLayout: SwipeRefreshLayout) {
    val scrollListener = object : RecyclerView.OnScrollListener(){
        override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
            val layoutManager = recyclerView.layoutManager as LinearLayoutManager
            // 当前能完全显示的第一个item的位置
            val firstCompletelyVisibleItemPosition = layoutManager.findFirstCompletelyVisibleItemPosition()
            // 需要去到顶部才能支持下拉刷新
            srLayout.isEnabled = firstCompletelyVisibleItemPosition <= 0
            if (firstCompletelyVisibleItemPosition > 0) srLayout.isRefreshing = false
        }
    }
    this.addOnScrollListener(scrollListener)
}